<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <input v-model="username" type="text" placeholder="用户名" required />
      </div>
      <div>
        <input v-model="password" type="password" placeholder="密码" required />
      </div>
      <button type="submit">登录</button>
      <p>没有账号？<router-link to="/register">注册</router-link></p>
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p> <!-- 错误信息 -->
    </form>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()

    // 定义数据绑定和错误信息
    const username = ref('')
    const password = ref('')
    const errorMessage = ref('')

    // 处理登录逻辑
    const handleLogin = async () => {
      try {
        // 发送 POST 请求到后端
        const response = await axios.post('http://localhost:9001/user/login', 
        {
            username: username.value,
            password: password.value
          }
      )
        // 如果后端返回 token
        if (response.data) {
          console.log('登录成功:', response.data)
          router.push('/homepage')
          // 将 token 存储在 localStorage 中
          localStorage.setItem('token', response.data.token)
          // 登录成功后跳转到 dashboard 页面
        } else {
          errorMessage.value = '登录失败'
        }
      } catch (error) {
        console.error('登录失败:', error)
        errorMessage.value = '登录请求失败，请重试'
      }
    }

    return {
      username,
      password,
      handleLogin,
      errorMessage
    }
  }
}
</script>

<style scoped>
.login {
  max-width: 300px;
  margin: auto;
  padding: 20px;
  background-color: #f4f4f4;
  border-radius: 8px;
}

h2 {
  text-align: center;
}

input {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #2c9b6f;
}

.error-message {
  color: red;
  font-size: 14px;
  text-align: center;
}
</style>
